<template>
  <a-spin :spinning="loading">
    <a-form v-bind="formItemLayout">
      <a-row>
        <a-col :span="12">
          <a-form-item label="项目" v-bind="validateInfos.projectId">
	          <j-search-select v-model:value="formData.projectId" dict="tm_project,project_name,id" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="工作类型" v-bind="validateInfos.workDayType">
	          <j-dict-select-tag v-model:value="formData.workDayType" dictCode="work_day_type" placeholder="请选择工作类型" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="今日工作事项" v-bind="validateInfos.dailyWorkContent">
	          <a-textarea v-model:value="formData.dailyWorkContent" :rows="4" placeholder="请输入今日工作事项" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="明日工作计划" v-bind="validateInfos.tomorrowWorkPlan">
	          <a-textarea v-model:value="formData.tomorrowWorkPlan" :rows="4" placeholder="请输入明日工作计划" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="工作开始时间" v-bind="validateInfos.dailyStartDate">
		        <a-date-picker placeholder="请选择工作开始时间"  v-model:value="formData.dailyStartDate" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="工作结束时间" v-bind="validateInfos.dailyEndDate">
		        <a-date-picker placeholder="请选择工作结束时间"  v-model:value="formData.dailyEndDate" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="待办事项" v-bind="validateInfos.todoContent">
            <a-textarea v-model:value="formData.todoContent" :rows="4" placeholder="请输入待办事项" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
        </a-col>
        <a-col :span="12">
          <a-form-item label="是否有风险" v-bind="validateInfos.isRisk">
	          <j-dict-select-tag v-model:value="formData.isRisk" dictCode="yes_or_no" placeholder="请选择是否有风险" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="风险内容" v-bind="validateInfos.riskContent">
	          <a-textarea v-model:value="formData.riskContent" :rows="4" placeholder="请输入风险内容" :disabled="disabled"/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated>
      <a-tab-pane tab="日报内容" key="dailyItem" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="dailyItemTableRef"
          :loading="dailyItemTable.loading"
          :columns="dailyItemTable.columns"
          :dataSource="dailyItemTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryDailyItemListByMainId, queryDataById, saveOrUpdate } from '../DailyManage.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {dailyItemColumns} from '../DailyManage.data';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import { Form } from 'ant-design-vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "DailyManageForm",
    components:{
      JDictSelectTag,
      JSearchSelect,
      JVxeTable,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const dailyItemTableRef = ref();
      const dailyItemTable = reactive<Record<string, any>>({
        loading: false,
        columns: dailyItemColumns,
        dataSource: []
      });
      const activeKey = ref('dailyItem');
      const formData = reactive<Record<string, any>>({
        id: '',
        projectId: '',
        workDayType: '',
        dailyWorkContent: '',
        tomorrowWorkPlan: '',
        dailyStartDate: '',
        dailyEndDate: '',
        isRisk: '',
        riskContent: '',
        todoContent: ''
      });

      //表单验证
      const validatorRules = reactive({
        projectId: [{ required: true, message: '请输入项目!'},],
        workDayType: [{ required: true, message: '请输入工作类型!'},],
        dailyWorkContent: [{ required: true, message: '请输入今日工作事项!'},],
        tomorrowWorkPlan: [{ required: true, message: '请输入明日工作计划!'},],
        dailyStartDate: [{ required: true, message: '请输入工作开始时间!'},],
        dailyEndDate: [{ required: true, message: '请输入工作结束时间!'},],
        isRisk: [{ required: true, message: '请输入是否有风险!'},],
        riskContent: [{ required: true, message: '请输入风险内容!'},],
        todoContent: [{ required: true, message: '请输入待办!'},],
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: true});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
      };

      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });



      function add() {
        resetFields();
        dailyItemTable.dataSource = [];
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const dailyItemDataList = await queryDailyItemListByMainId(row['id']);
        dailyItemTable.dataSource = [...dailyItemDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        Object.keys(row).map(k => {
          formData[k] = row[k];
        });
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'dailyItem': dailyItemTableRef,
      });

      async function getFormData() {
        await validate();
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values)
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }

      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }


      return {
        dailyItemTableRef,
        dailyItemTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit
      }
    }
  });
</script>
